<?php

namespace App\Services\User;

use App\Exceptions\LoginException;
use App\Helpers\FileHelper;
use App\Helpers\MvcHelper;
use App\Models\Admin\User\UserModel;
use Exception;
use Illuminate\Support\Facades\DB;
use Random\RandomException;

class UserService extends BaseUserService
{

    /**
     * 获取用户数据
     *
     * @param int $userId
     * @return array
     * @throws Exception
     */
    public function getCheckUserInfo(int $userId): array
    {
        return $this->getUserModel()->getItemById($userId, UserModel::USER_LOGIN_CACHE_FIELDS);
    }

    /**
     * 检测用户是否禁用
     *
     * @param int $forbidden 状态
     * @return bool
     */
    public function checkForbidden(int $forbidden): bool
    {
        return $forbidden === UserModel::ENABLE_FREEZE;
    }

    /**
     * 用户详情
     *
     * @return array
     * @throws Exception
     */
    public function userInfo(): array
    {
        // 获取用户信息
        $userInfo = $this->getUserModel()->getItemById(MvcHelper::getLoginUserId(), [
            'id', 'uuid', 'phone', 'email', 'username', 'nickname', 'header_img', 'authority_id', 'introduction', 'side_mode', 'active_color', 'base_color',
        ]);

        // 查询角色列表
        $authority = $this->getAuthoritiesModel()->getItemById($userInfo['authority_id']);

        return [
            'id'           => $userInfo['id'],
            'nickname'     => $userInfo['nickname'],
            'email'        => $userInfo['email'],
            'uuid'         => $userInfo['uuid'],
            'phone'        => $userInfo['phone'],
            'name'         => $userInfo['nickname'],
            'headerImg'    => $userInfo['header_img'],
            'sideMode'     => $userInfo['side_mode'],
            'activeColor'  => $userInfo['active_color'],
            'introduction' => $userInfo['introduction'],
            'baseColor'    => $userInfo['base_color'],
            'authority'    => $authority,
        ];
    }

    /**
     * 用户列表
     *
     * @param array $params
     * @return array
     */
    public function userList(array $params): array
    {
        // 总条数
        $total    = $this->getUserModel()->getTotal($params);
        $userList = $this->getUserModel()->getList($params, [
            'id', 'header_img', 'username', 'nickname', 'phone', 'email', 'authority_id', 'enable',
        ]);

        $userIds = array_column($userList, 'id');

        // 根据用户ids获取用户权限ids
        $userAuthorityList = $this->getUserAuthorityModel()->getItemsByUserIds($userIds, [
            'user_id', 'authority_id',
        ]);

        $authorityIds = array_column($userAuthorityList, 'authority_id');
        // 查询角色列表
        $authorityList    = $this->getAuthoritiesModel()->getItemsByIds($authorityIds, [
            'id', 'parent_id', 'name', 'default_router',
        ]);
        $authorityListMap = array_column($authorityList, null, 'id');

        $userAuthorListMap = [];
        foreach ($userAuthorityList as $item) {
            $userAuthorListMap[$item['user_id']][] = [
                'authorityId'   => $item['authority_id'],
                'parentId'      => $authorityListMap[$item['authority_id']]['parent_id'],
                'name'          => $authorityListMap[$item['authority_id']]['name'],
                'defaultRouter' => $authorityListMap[$item['authority_id']]['default_router'],
            ];
        }

        $list = [];
        foreach ($userList as $item) {
            $list[] = [
                'id'          => $item['id'],
                'headerImg'   => FileHelper::getCompleteAvtar($item['header_img']),
                'username'    => $item['username'],
                'nickname'    => $item['nickname'],
                'phone'       => $item['phone'],
                'email'       => $item['email'],
                'authorities' => $userAuthorListMap[$item['id']] ?? '',
                'enable'      => $item['enable'],
            ];
        }

        return [
            'list'  => $list,
            'total' => $total,
        ];
    }

    /**
     * 设置用户角色
     *
     * @param array $params
     * @return void
     */
    public function setUserAuthorities(array $params): void
    {
        $createUserAuthorityList = [];
        foreach ($params['authorityIds'] as $authorityId) {
            $createUserAuthorityList[] = [
                'user_id'      => $params['id'],
                'authority_id' => $authorityId,
            ];
        }

        // 设置用户角色
        DB::transaction(function () use ($params, $createUserAuthorityList) {
            // 删除之前的用户角色关系
            $this->getUserAuthorityModel()->deleteItemByUserId($params['id']);
            // 添加新的用户角色关系
            $createUserAuthorityList && $this->getUserAuthorityModel()->addItem($createUserAuthorityList);
            // 更新用户表的角色id
            $this->getUserModel()->updateItemById($params['id'], [
                'authority_id' => $createUserAuthorityList[0]['authority_id'] ?? 0,
            ]);
        });
    }

    /**
     * 重置密码
     *
     * @param array $params
     * @return void
     * @throws LoginException
     */
    public function resetPassword(array $params): void
    {
        // 查询用户是否存在
        $userInfo = $this->getUserModel()->getItemById($params['id'], ['id']);
        if (empty($userInfo)) {
            throw new LoginException('用户不存在', LoginException::CODE_1011);
        }

        // @tips 重置密码 为 123456
        $this->getUserModel()->updateItemById($params['id'], [
            'password' => encryption("123456"),
        ]);
    }

    /**
     * 删除用户
     *
     * @param array $params
     * @return void
     * @throws LoginException
     */
    public function deleteUser(array $params): void
    {
        if (MvcHelper::getLoginUserId() == $params['id']) {
            throw new LoginException('删除失败, 自杀失败', LoginException::CODE_1011);
        }

        // 查询用户是否存在
        $userInfo = $this->getUserModel()->getItemById($params['id'], ['id']);
        if (empty($userInfo)) {
            throw new LoginException('用户不存在', LoginException::CODE_1011);
        }

        // 删除用户
        DB::transaction(function () use ($userInfo, $params) {
            // 删除用户
            $this->getUserModel()->deleteItemById($params['id']);
            // 删除用户角色关联数据
            $this->getUserAuthorityModel()->deleteItemByUserId($params['id']);
        });
    }

    /**
     * 设置自身信息
     *
     * @param array $params
     * @return void
     */
    public function setSelfInfo(array $params): void
    {
        $userId = MvcHelper::getLoginUserId();

        $updateUserData = [];
        if (!empty($params['nickname'])) {
            $updateUserData['nickname'] = $params['nickname'];
        }
        if (!empty($params['phone'])) {
            $updateUserData['phone'] = $params['phone'];
        }
        if (!empty($params['email'])) {
            $updateUserData['email'] = $params['email'];
        }

        $this->getUserModel()->updateItemById($userId, $updateUserData);
    }

    /**
     * 更新密码
     *
     * @param array $params
     * @return void
     */
    public function changePassword(array $params): void
    {
        $this->getUserModel()->updateItemById(MvcHelper::getLoginUserId(), [
            'password' => encryption($params['password']),
        ]);

    }

    /**
     * 注册
     *
     * @param array $params
     * @return void
     * @throws LoginException
     * @throws RandomException
     */
    public function createUser(array $params): void
    {
        // 查询用户名是否注册过
        $userInfo = $this->getUserModel()->getItemByUsername($params['username'], ['id']);
        if (!empty($userInfo)) {
            throw new LoginException('', LoginException::CODE_1001);
        }

        // 添加的用户信息
        $createUserData = [
            'username'     => $params['username'],
            'password'     => encryption($params['password']),
            'nickname'     => $params['nickname'],
            'enable'       => $params['enable'],
            'phone'        => $params['phone'],
            'email'        => $params['email'],
            'authority_id' => $params['authorityId'],
            'uuid'         => generateUuid(),
        ];
        if (!empty($params['headerImg'])) {
            $createUserData['header_img'] = $params['headerImg'];
        }

        DB::transaction(function () use ($params, $createUserData) {
            // 添加用户信息
            $userId = $this->getUserModel()->addItemGetId($createUserData);
            // 添加的用户角色信息
            $createUserAuthorityList = [];
            foreach ($params['authorityIds'] as $item) {
                $createUserAuthorityList[] = [
                    'user_id'      => $userId,
                    'authority_id' => $item,
                ];
            }
            // 添加用户角色信息
            $this->getUserAuthorityModel()->addItem($createUserAuthorityList);
        });
    }

    /**
     * 设置用户信息
     *
     * @param array $params
     * @return void
     */
    public function setUserInfo(array $params): void
    {
        $createUserAuthorityList = [];
        if ($params['authorityIds']) {
            foreach ($params['authorityIds'] as $authorityId) {
                $createUserAuthorityList[] = [
                    'user_id'      => $params['id'],
                    'authority_id' => $authorityId,
                ];
            }
        }

        $updateUserData = [
            'nickname'     => $params['nickname'],
            'header_img'   => $params['headerImg'],
            'phone'        => $params['phone'],
            'email'        => $params['email'],
            'enable'       => $params['enable'],
            'authority_id' => $params['authorityIds'][0] ?? 0,
        ];

        DB::transaction(function () use ($params, $createUserAuthorityList, $updateUserData) {
            // 删除之前的用户角色关系
            $this->getUserAuthorityModel()->deleteItemByUserId($params['id']);
            // 添加新的用户角色关系
            $createUserAuthorityList && $this->getUserAuthorityModel()->addItem($createUserAuthorityList);
            // 更新用户信息
            $this->getUserModel()->updateItemById($params['id'], $updateUserData);
        });
    }
}
